<template>
  <div>
    <el-form ref="listingTemplateFormRef" label-position="top" :model="listingTemplateForm">
<!--      <el-form-item-->
<!--        label="店铺"-->
<!--        prop="storeValue"-->
<!--        :rules="[-->
<!--          {-->
<!--            required: true,-->
<!--            message: '选择店铺',-->
<!--            trigger: 'change',-->
<!--          },-->
<!--        ]"-->
<!--      >-->
<!--        <el-select v-model="listingTemplateForm.storeValue" filterable>-->
<!--          <el-option v-for="item in storeOption" :key="item.value" :label="item.label" :value="item.value" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="品牌名称"
            prop="brand"
            :rules="[
              {
                required: true,
                message: '请输入品牌名称',
                trigger: 'blur',
              },
            ]"
          >
            <el-input placeholder="品牌名称" maxlength="100" show-word-limit v-model="listingTemplateForm.brand" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="原产地国家"
            prop="countryOfOrigin"
            :rules="[
              {
                required: true,
                message: '请输入原产地国家',
                trigger: 'blur',
              },
            ]"
          >
            <el-input placeholder="原产地国家" maxlength="2" show-word-limit v-model="listingTemplateForm.countryOfOrigin" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="厂商名称"
            prop="manufacturer"
            :rules="[
              {
                required: true,
                message: '请输入厂商名称',
                trigger: 'blur',
              },
            ]"
          >
            <el-input placeholder="厂商名称" maxlength="100" show-word-limit v-model="listingTemplateForm.manufacturer" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="厂商编号"
            prop="manufacturerNumber"
            :rules="[
              {
                required: true,
                message: '请输入厂商编号',
                trigger: 'blur',
              },
            ]"
          >
            <el-input placeholder="厂商编号" maxlength="100" show-word-limit v-model="listingTemplateForm.manufacturerNumber" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="SKU前缀"
            prop="skuPrefix"
            :rules="[
              {
                required: true,
                message: '请输入SKU前缀',
                trigger: 'blur',
              },
            ]"
          >
            <el-input style="width: 100%" placeholder="YH_" v-model="listingTemplateForm.skuPrefix" :maxlength="20" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="最晚发货时长（天）"
            prop="shipMaxDay"
            :rules="[
              {
                required: true,
                message: '请输入最晚发货时长',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number
              style="width: 100%"
              placeholder="最晚发货时长（天）"
              v-model="listingTemplateForm.shipMaxDay"
              :min="0"
              controls-position="right"
            >
              <template #suffix>
                <span>天</span>
              </template>
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="库存数量"
            prop="stockNumber"
            :rules="[
              {
                required: true,
                message: '请输入库存数量',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number
              style="width: 100%"
              placeholder="库存数量"
              v-model="listingTemplateForm.stockNumber"
              :min="1"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大订单数量" prop="maxOrderQuantity">
            <el-input-number
              style="width: 100%"
              placeholder="允许购买最大订单数量"
              v-model="listingTemplateForm.maxOrderQuantity"
              :min="0"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item
        label="价格调整"
        prop="fluctuationPrice.fluctuation"
        :rules="[
          {
            required: true,
            message: '请输入调整价格比例',
            trigger: 'blur',
          },
        ]"
      >
        <el-row :gutter="20" class="w-full">
          <el-col :span="12">
            <el-input v-model="listingTemplateForm.fluctuationPrice.fluctuation" placeholder="调整价格比例" controls-position="right" />
          </el-col>
          <el-col :span="6" style="padding-left: 20px">
            <el-radio-group v-model="listingTemplateForm.fluctuationPrice.direction">
              <el-radio :value="'up'">增加</el-radio>
              <el-radio :value="'down'">减少</el-radio>
            </el-radio-group>
          </el-col>
          <el-col :span="6">
            <el-radio-group v-model="listingTemplateForm.fluctuationPrice.fluctuationType">
              <el-radio :value="'percentage'">百分比</el-radio>
              <el-radio :value="'fixed'">固定值</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        label="模板名称"
        prop="name"
        :rules="[
          {
            required: true,
            message: '请输入模板名称',
            trigger: 'blur',
          },
        ]"
      >
        <el-input placeholder="模板名称" maxlength="200" show-word-limit v-model="listingTemplateForm.name" />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="标题前缀" prop="titlePrefix">
            <el-input placeholder="在标题前添加文字" maxlength="200" show-word-limit v-model="listingTemplateForm.titlePrefix" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标题后缀" prop="titleSuffix">
            <el-input placeholder="在标题后添加文字" maxlength="200" show-word-limit v-model="listingTemplateForm.titleSuffix" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="临时替换" prop="titlePrefix">
            <el-row :gutter="16" class="w-full mb-3" v-for="(ite, index) in listingTemplateForm.replaceStrList" :key="'replaceStrList' + index">
              <el-col :span="9">
                <el-input placeholder="将词语" maxlength="200" show-word-limit v-model="ite.oldStr" />
              </el-col>
              <el-col :span="9">
                <el-input placeholder="替换成" maxlength="200" show-word-limit v-model="ite.newStr" />
              </el-col>
              <el-col :span="6">
                <el-checkbox v-model="ite.replaceType" :true-value="'title'" label="只替换标题" />
                <el-button
                  v-if="index > 0"
                  style="vertical-align: bottom; margin-left: 5px"
                  text
                  type="primary"
                  @click="onReplaceStrListDelete(index)"
                  :icon="Delete"
                  circle
                />
              </el-col>
            </el-row>
            <el-button :icon="Plus" text type="primary" @click="listingTemplateForm.replaceStrList.push({ oldStr: '', newStr: '', replaceType: '' })"
              >添加</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="热门关键字" prop="keywordPrefix">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="插入商品原有的关键字之前"
              maxlength="250"
              show-word-limit
              v-model="listingTemplateForm.keywordPrefix"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="后面追加" prop="keywordSuffix">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="追加到原有关键词之后"
              maxlength="250"
              show-word-limit
              v-model="listingTemplateForm.keywordSuffix"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="要点说明" prop="bulletPointPrefix">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="插入商品原有的要点说明之前，使用回车分割"
              maxlength="2000"
              show-word-limit
              v-model="listingTemplateForm.bulletPointPrefix"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="后面追加" prop="bulletPointSuffix">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="追加到产品要点说明之后"
              maxlength="2000"
              show-word-limit
              v-model="listingTemplateForm.bulletPointSuffix"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="插入描述" prop="descriptionPrefix">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="插入到产品描述之前"
              maxlength="2000"
              show-word-limit
              v-model="listingTemplateForm.descriptionPrefix"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="后面追加" prop="descriptionSuffix">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="追加到产品描述之后"
              maxlength="2000"
              show-word-limit
              v-model="listingTemplateForm.descriptionSuffix"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { Plus, Delete } from '@element-plus/icons-vue'

import { findStoreByNotPage, getListingTemplate, listingTemplate } from '@/api/common'
import { HttpAsk } from '@/plugins/util/axios'
import { ElMessage, FormInstance } from 'element-plus'
import { objCopyProperties } from '@/plugins/util/common'
interface StoreOption {
  value: string
  label: string
  marketplace: any
}
interface ReplaceStrList {
  oldStr: string
  newStr: string
  replaceType: string
}
interface FluctuationPrice {
  direction: string
  fluctuation: string
  fluctuationType: string
}
interface ListingTemplateForm {
  id: string | null
  storeValue: string
  storeId: string
  skuPrefix: string
  marketplace: string
  marketplaceName: string
  name: string
  brand: string
  countryOfOrigin: string
  manufacturer: string
  manufacturerNumber: string
  stockNumber: number
  maxOrderQuantity: number
  titlePrefix: string
  titleSuffix: string
  replaceStrList: ReplaceStrList[]
  keywordPrefix: string
  keywordSuffix: string
  bulletPointPrefix: string
  bulletPointSuffix: string
  descriptionPrefix: string
  descriptionSuffix: string
  shipMaxDay: number
  fluctuationPrice: FluctuationPrice
  version: number
}
const defaultListingTemplateForm: ListingTemplateForm = {
  id: null,
  storeValue: '',
  storeId: '',
  skuPrefix: '',
  marketplace: '',
  marketplaceName: '',
  name: '',
  brand: '',
  countryOfOrigin: 'CH',
  manufacturer: '',
  manufacturerNumber: '',
  stockNumber: 1,
  maxOrderQuantity: 0,
  shipMaxDay: 10,
  titlePrefix: '',
  titleSuffix: '',
  replaceStrList: [
    {
      oldStr: '',
      newStr: '',
      replaceType: '',
    },
  ],
  keywordPrefix: '',
  keywordSuffix: '',
  bulletPointPrefix: '',
  bulletPointSuffix: '',
  descriptionPrefix: '',
  descriptionSuffix: '',
  fluctuationPrice: {
    direction: 'up',
    fluctuation: '',
    fluctuationType: 'percentage',
  },
  version: 0,
}
const listingTemplateFormRef = ref<FormInstance>()
const listingTemplateForm = ref<ListingTemplateForm>({ ...defaultListingTemplateForm })
const storeOption = ref<StoreOption[]>([])
const templateName = computed(() => {
  let storeName = storeOption.value.find((item) => {
    return item.value === listingTemplateForm.value.storeValue
  })?.label
  let tempArray: string[] = []
  if (storeName) {
    tempArray.push(`店铺:${storeName}`)
  }
  if (listingTemplateForm.value.brand) {
    tempArray.push(`品牌:${listingTemplateForm.value.brand}`)
  }
  if (listingTemplateForm.value.stockNumber) {
    tempArray.push(`库存数量:${listingTemplateForm.value.stockNumber}`)
  }
  if (listingTemplateForm.value.fluctuationPrice.fluctuation) {
    let fluctuationPrice = listingTemplateForm.value.fluctuationPrice
    tempArray.push(
      `价格调整:${fluctuationPrice.direction === 'up' ? '增加' : '减少'}${fluctuationPrice.fluctuationType === 'percentage' ? '百分比' : '固定值'}${fluctuationPrice.fluctuation}`
    )
  }
  return tempArray.join(';')
})
const onReplaceStrListDelete = (index: number) => {
  listingTemplateForm.value.replaceStrList.splice(index, 1)
}
const reqFindStoreByNotPage = () => {
  findStoreByNotPage().then((res) => {
    storeOption.value = []
    res.data.forEach((item: any) => {
      item.marketplace.forEach((marketplace: any) => {
        storeOption.value.push({
          value: `${item.id}-${marketplace.code}`,
          label: `${item.name}/${marketplace.name}`,
          marketplace: marketplace,
        })
      })
    })
  })
}
defineExpose({
  async onConfirm() {
    const isValid = await new Promise((resolve) => {
      listingTemplateFormRef.value?.validate((valid) => {
        resolve(valid)
      })
    })
    if (isValid) {
      if (listingTemplateForm.value.storeValue) {
        listingTemplateForm.value.storeId = listingTemplateForm.value.storeValue.split('-')[0]
        listingTemplateForm.value.marketplace = listingTemplateForm.value.storeValue.split('-')[1]
        let storeObj = storeOption.value.find((item) => {
          return item.value === listingTemplateForm.value.storeValue
        })
        listingTemplateForm.value.marketplaceName = storeObj?.marketplace?.name
      }
      const res = await listingTemplate(listingTemplateForm.value)
      if (res.code === HttpAsk.SUCCESS) {
        ElMessage.success('操作成功')
      }
    } else {
      throw new Error('表单验证失败')
    }
  },
  onOpen() {
    listingTemplateForm.value = { ...defaultListingTemplateForm }
    listingTemplateFormRef.value?.resetFields()
  },
  async onOpened() {
    await new Promise((resolve) => {
      if (props.templateId) {
        getListingTemplate(props.templateId).then((res) => {
          if (res.code === HttpAsk.SUCCESS) {
            objCopyProperties(res.data, listingTemplateForm.value, true)
            listingTemplateForm.value.storeValue = res.data.storeId + '-' + res.data.marketplace
            resolve(1)
          }
        })
      } else {
        resolve(1)
      }
    })
  },
})
const props = defineProps({
  templateId: {
    type: String,
    default: '',
  },
})
watch(templateName, (newValue) => {
  listingTemplateForm.value.name = newValue
})

onMounted(() => {
  reqFindStoreByNotPage()
})
</script>
<style scoped lang="scss"></style>
